package com.zenithmind.chat.controller;

import com.zenithmind.chat.pojo.vo.ChatPrivateSessionUserVO;
import com.zenithmind.chat.service.ChatPrivateSessionUserService;
import com.zenithmind.common.context.UserContext;
import com.zenithmind.common.result.Result;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotEmpty;
import java.time.LocalDateTime;
import java.util.List;

/**
 * 私聊会话用户关系控制器 - 遵循单一职责原则
 * 只负责私聊会话用户关系的HTTP接口处理
 * 
 * @author ZenithMind Team
 * @since 2025-01-09
 */
@Slf4j
@RestController
@RequestMapping("/api/chat/private-session-users")
@RequiredArgsConstructor
@Validated
@Tag(name = "私聊会话用户关系管理", description = "私聊会话用户关系相关接口")
public class ChatPrivateSessionUserController {

    private final ChatPrivateSessionUserService chatPrivateSessionUserService;

    @PostMapping("/create")
    @Operation(summary = "创建会话用户关系", description = "创建私聊会话用户关系")
    public Result<String> createSessionUser(
            @Parameter(description = "会话ID") @RequestParam @NotBlank String sessionId,
            @Parameter(description = "用户ID") @RequestParam @NotBlank String userId) {
        String relationId = chatPrivateSessionUserService.createSessionUser(sessionId, userId);
        return Result.success(relationId);
    }

    @PostMapping("/batch-create")
    @Operation(summary = "批量创建会话用户关系", description = "批量创建私聊会话用户关系")
    public Result<Boolean> batchCreateSessionUsers(
            @Parameter(description = "会话ID") @RequestParam @NotBlank String sessionId,
            @RequestBody @NotEmpty List<String> userIds) {
        Boolean result = chatPrivateSessionUserService.batchCreateSessionUsers(sessionId, userIds);
        return Result.success(result);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除会话用户关系", description = "删除私聊会话用户关系")
    public Result<Boolean> deleteSessionUser(
            @Parameter(description = "会话ID") @RequestParam @NotBlank String sessionId,
            @Parameter(description = "用户ID") @RequestParam @NotBlank String userId) {
        Boolean result = chatPrivateSessionUserService.deleteSessionUser(sessionId, userId);
        return Result.success(result);
    }

    @GetMapping("/session/{sessionId}/users")
    @Operation(summary = "查询会话用户列表", description = "根据会话ID查询用户列表")
    public Result<List<ChatPrivateSessionUserVO>> getUsersBySessionId(
            @Parameter(description = "会话ID") @PathVariable @NotBlank String sessionId) {
        List<ChatPrivateSessionUserVO> users = chatPrivateSessionUserService.getUsersBySessionId(sessionId);
        return Result.success(users);
    }

    @GetMapping("/user/{userId}/sessions")
    @Operation(summary = "查询用户会话列表", description = "根据用户ID查询会话列表")
    public Result<List<ChatPrivateSessionUserVO>> getSessionsByUserId(
            @Parameter(description = "用户ID") @PathVariable @NotBlank String userId) {
        List<ChatPrivateSessionUserVO> sessions = chatPrivateSessionUserService.getSessionsByUserId(userId);
        return Result.success(sessions);
    }

    @GetMapping("/session-user")
    @Operation(summary = "查询会话用户关系", description = "查询指定会话和用户的关系")
    public Result<ChatPrivateSessionUserVO> getSessionUser(
            @Parameter(description = "会话ID") @RequestParam @NotBlank String sessionId,
            @Parameter(description = "用户ID") @RequestParam @NotBlank String userId) {
        ChatPrivateSessionUserVO sessionUser = chatPrivateSessionUserService.getSessionUser(sessionId, userId);
        return Result.success(sessionUser);
    }

    @GetMapping("/check-user-in-session")
    @Operation(summary = "检查用户是否在会话中", description = "检查用户是否在指定会话中")
    public Result<Boolean> isUserInSession(
            @Parameter(description = "会话ID") @RequestParam @NotBlank String sessionId,
            @Parameter(description = "用户ID") @RequestParam @NotBlank String userId) {
        Boolean isInSession = chatPrivateSessionUserService.isUserInSession(sessionId, userId);
        return Result.success(isInSession);
    }

    @PutMapping("/update-access-time")
    @Operation(summary = "更新最后访问时间", description = "更新用户对会话的最后访问时间")
    public Result<Boolean> updateLastAccessTime(
            @Parameter(description = "会话ID") @RequestParam @NotBlank String sessionId,
            @Parameter(description = "用户ID") @RequestParam @NotBlank String userId,
            @Parameter(description = "最后访问时间") @RequestParam(required = false) 
            @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime lastAccessTime) {
        Boolean result;
        if (lastAccessTime != null) {
            result = chatPrivateSessionUserService.updateLastAccessTime(sessionId, userId, lastAccessTime);
        } else {
            result = chatPrivateSessionUserService.updateLastAccessTimeToNow(sessionId, userId);
        }
        return Result.success(result);
    }

    @PutMapping("/update-unread-count")
    @Operation(summary = "更新未读消息数", description = "更新用户在会话中的未读消息数")
    public Result<Boolean> updateUnreadCount(
            @Parameter(description = "会话ID") @RequestParam @NotBlank String sessionId,
            @Parameter(description = "用户ID") @RequestParam @NotBlank String userId,
            @Parameter(description = "未读消息数") @RequestParam Integer unreadCount) {
        Boolean result = chatPrivateSessionUserService.updateUnreadCount(sessionId, userId, unreadCount);
        return Result.success(result);
    }

    @PostMapping("/increment-unread")
    @Operation(summary = "增加未读消息数", description = "为用户在会话中增加未读消息数")
    public Result<Boolean> incrementUnreadCount(
            @Parameter(description = "会话ID") @RequestParam @NotBlank String sessionId,
            @Parameter(description = "用户ID") @RequestParam @NotBlank String userId) {
        Boolean result = chatPrivateSessionUserService.incrementUnreadCount(sessionId, userId);
        return Result.success(result);
    }

    @PostMapping("/clear-unread")
    @Operation(summary = "清零未读消息数", description = "清零用户在会话中的未读消息数")
    public Result<Boolean> clearUnreadCount(
            @Parameter(description = "会话ID") @RequestParam @NotBlank String sessionId,
            @Parameter(description = "用户ID") @RequestParam @NotBlank String userId) {
        Boolean result = chatPrivateSessionUserService.clearUnreadCount(sessionId, userId);
        return Result.success(result);
    }

    @PostMapping("/batch-clear-unread")
    @Operation(summary = "批量清零未读消息数", description = "批量清零用户在多个会话中的未读消息数")
    public Result<Boolean> batchClearUnreadCount(
            @RequestBody @NotEmpty List<String> sessionIds,
            @Parameter(description = "用户ID") @RequestParam @NotBlank String userId) {
        Boolean result = chatPrivateSessionUserService.batchClearUnreadCount(sessionIds, userId);
        return Result.success(result);
    }

    @PutMapping("/update-top-status")
    @Operation(summary = "更新置顶状态", description = "更新会话的置顶状态")
    public Result<Boolean> updateTopStatus(
            @Parameter(description = "会话ID") @RequestParam @NotBlank String sessionId,
            @Parameter(description = "用户ID") @RequestParam @NotBlank String userId,
            @Parameter(description = "是否置顶") @RequestParam Boolean isTop) {
        Boolean result = chatPrivateSessionUserService.updateTopStatus(sessionId, userId, isTop);
        return Result.success(result);
    }

    @PutMapping("/update-mute-status")
    @Operation(summary = "更新免打扰状态", description = "更新会话的免打扰状态")
    public Result<Boolean> updateMuteStatus(
            @Parameter(description = "会话ID") @RequestParam @NotBlank String sessionId,
            @Parameter(description = "用户ID") @RequestParam @NotBlank String userId,
            @Parameter(description = "是否免打扰") @RequestParam Boolean isMuted) {
        Boolean result = chatPrivateSessionUserService.updateMuteStatus(sessionId, userId, isMuted);
        return Result.success(result);
    }

    @GetMapping("/user/{userId}/top-sessions")
    @Operation(summary = "查询置顶会话", description = "查询用户的置顶会话列表")
    public Result<List<ChatPrivateSessionUserVO>> getTopSessionsByUserId(
            @Parameter(description = "用户ID") @PathVariable @NotBlank String userId) {
        List<ChatPrivateSessionUserVO> topSessions = chatPrivateSessionUserService.getTopSessionsByUserId(userId);
        return Result.success(topSessions);
    }

    @GetMapping("/user/{userId}/muted-sessions")
    @Operation(summary = "查询免打扰会话", description = "查询用户的免打扰会话列表")
    public Result<List<ChatPrivateSessionUserVO>> getMutedSessionsByUserId(
            @Parameter(description = "用户ID") @PathVariable @NotBlank String userId) {
        List<ChatPrivateSessionUserVO> mutedSessions = chatPrivateSessionUserService.getMutedSessionsByUserId(userId);
        return Result.success(mutedSessions);
    }

    @GetMapping("/user/{userId}/total-unread")
    @Operation(summary = "统计用户未读消息总数", description = "统计用户的未读消息总数")
    public Result<Long> countTotalUnreadByUserId(
            @Parameter(description = "用户ID") @PathVariable @NotBlank String userId) {
        Long totalUnread = chatPrivateSessionUserService.countTotalUnreadByUserId(userId);
        return Result.success(totalUnread);
    }

    @GetMapping("/session-unread")
    @Operation(summary = "查询会话未读消息数", description = "查询用户在指定会话的未读消息数")
    public Result<Integer> getUnreadCountBySession(
            @Parameter(description = "会话ID") @RequestParam @NotBlank String sessionId,
            @Parameter(description = "用户ID") @RequestParam @NotBlank String userId) {
        Integer unreadCount = chatPrivateSessionUserService.getUnreadCountBySession(sessionId, userId);
        return Result.success(unreadCount);
    }

    @GetMapping("/user/{userId}/active-sessions")
    @Operation(summary = "查询活跃会话", description = "查询用户的活跃会话列表")
    public Result<List<ChatPrivateSessionUserVO>> getActiveSessionsByUserId(
            @Parameter(description = "用户ID") @PathVariable @NotBlank String userId,
            @Parameter(description = "数量限制") @RequestParam(defaultValue = "10") Integer limit) {
        List<ChatPrivateSessionUserVO> activeSessions = chatPrivateSessionUserService.getActiveSessionsByUserId(userId, limit);
        return Result.success(activeSessions);
    }

    @PutMapping("/update-read-time")
    @Operation(summary = "更新最后阅读时间", description = "更新用户对会话的最后阅读时间")
    public Result<Boolean> updateLastReadTime(
            @Parameter(description = "会话ID") @RequestParam @NotBlank String sessionId,
            @Parameter(description = "用户ID") @RequestParam @NotBlank String userId,
            @Parameter(description = "最后阅读时间") @RequestParam(required = false) 
            @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime lastReadTime) {
        Boolean result;
        if (lastReadTime != null) {
            result = chatPrivateSessionUserService.updateLastReadTime(sessionId, userId, lastReadTime);
        } else {
            result = chatPrivateSessionUserService.updateLastReadTimeToNow(sessionId, userId);
        }
        return Result.success(result);
    }

    @PutMapping("/batch-update-access-time")
    @Operation(summary = "批量更新最后访问时间", description = "批量更新用户对多个会话的最后访问时间")
    public Result<Boolean> batchUpdateLastAccessTime(
            @RequestBody @NotEmpty List<String> sessionIds,
            @Parameter(description = "用户ID") @RequestParam @NotBlank String userId,
            @Parameter(description = "最后访问时间") @RequestParam(required = false) 
            @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime lastAccessTime) {
        LocalDateTime accessTime = lastAccessTime != null ? lastAccessTime : LocalDateTime.now();
        Boolean result = chatPrivateSessionUserService.batchUpdateLastAccessTime(sessionIds, userId, accessTime);
        return Result.success(result);
    }

    @GetMapping("/session/{sessionId}/user-ids")
    @Operation(summary = "获取会话用户ID列表", description = "获取指定会话的所有用户ID")
    public Result<List<String>> getUserIdsBySessionId(
            @Parameter(description = "会话ID") @PathVariable @NotBlank String sessionId) {
        List<String> userIds = chatPrivateSessionUserService.getUserIdsBySessionId(sessionId);
        return Result.success(userIds);
    }

    @GetMapping("/user/{userId}/session-ids")
    @Operation(summary = "获取用户会话ID列表", description = "获取指定用户的所有会话ID")
    public Result<List<String>> getSessionIdsByUserId(
            @Parameter(description = "用户ID") @PathVariable @NotBlank String userId) {
        List<String> sessionIds = chatPrivateSessionUserService.getSessionIdsByUserId(userId);
        return Result.success(sessionIds);
    }

    @GetMapping("/check-common-session")
    @Operation(summary = "检查共同会话", description = "检查两个用户是否有共同会话")
    public Result<Boolean> hasCommonSession(
            @Parameter(description = "用户1ID") @RequestParam @NotBlank String userId1,
            @Parameter(description = "用户2ID") @RequestParam @NotBlank String userId2) {
        Boolean hasCommon = chatPrivateSessionUserService.hasCommonSession(userId1, userId2);
        return Result.success(hasCommon);
    }

    @GetMapping("/common-sessions")
    @Operation(summary = "获取共同会话列表", description = "获取两个用户的共同会话列表")
    public Result<List<ChatPrivateSessionUserVO>> getCommonSessions(
            @Parameter(description = "用户1ID") @RequestParam @NotBlank String userId1,
            @Parameter(description = "用户2ID") @RequestParam @NotBlank String userId2) {
        List<ChatPrivateSessionUserVO> commonSessions = chatPrivateSessionUserService.getCommonSessions(userId1, userId2);
        return Result.success(commonSessions);
    }

    @GetMapping("/user/{userId}/session-count")
    @Operation(summary = "统计用户会话数量", description = "统计用户的会话数量")
    public Result<Long> countSessionsByUserId(
            @Parameter(description = "用户ID") @PathVariable @NotBlank String userId) {
        Long sessionCount = chatPrivateSessionUserService.countSessionsByUserId(userId);
        return Result.success(sessionCount);
    }

    @GetMapping("/session/{sessionId}/user-count")
    @Operation(summary = "统计会话用户数量", description = "统计会话的用户数量")
    public Result<Long> countUsersBySessionId(
            @Parameter(description = "会话ID") @PathVariable @NotBlank String sessionId) {
        Long userCount = chatPrivateSessionUserService.countUsersBySessionId(sessionId);
        return Result.success(userCount);
    }

    @PostMapping("/cleanup-inactive")
    @Operation(summary = "清理不活跃关系", description = "清理不活跃的会话用户关系")
    public Result<Integer> cleanupInactiveSessionUsers(
            @Parameter(description = "不活跃天数") @RequestParam(defaultValue = "30") Integer inactiveDays) {
        Integer cleanedCount = chatPrivateSessionUserService.cleanupInactiveSessionUsers(inactiveDays);
        return Result.success(cleanedCount);
    }

    @PutMapping("/archive")
    @Operation(summary = "归档会话关系", description = "归档或取消归档会话用户关系")
    public Result<Boolean> archiveSessionUser(
            @Parameter(description = "会话ID") @RequestParam @NotBlank String sessionId,
            @Parameter(description = "用户ID") @RequestParam @NotBlank String userId,
            @Parameter(description = "是否归档") @RequestParam Boolean isArchived) {
        Boolean result = chatPrivateSessionUserService.archiveSessionUser(sessionId, userId, isArchived);
        return Result.success(result);
    }

    @GetMapping("/user/{userId}/archived-sessions")
    @Operation(summary = "查询归档会话", description = "查询用户的归档会话列表")
    public Result<List<ChatPrivateSessionUserVO>> getArchivedSessionsByUserId(
            @Parameter(description = "用户ID") @PathVariable @NotBlank String userId) {
        List<ChatPrivateSessionUserVO> archivedSessions = chatPrivateSessionUserService.getArchivedSessionsByUserId(userId);
        return Result.success(archivedSessions);
    }

    @PutMapping("/batch-archive")
    @Operation(summary = "批量归档会话关系", description = "批量归档或取消归档会话用户关系")
    public Result<Boolean> batchArchiveSessionUsers(
            @RequestBody @NotEmpty List<String> sessionIds,
            @Parameter(description = "用户ID") @RequestParam @NotBlank String userId,
            @Parameter(description = "是否归档") @RequestParam Boolean isArchived) {
        Boolean result = chatPrivateSessionUserService.batchArchiveSessionUsers(sessionIds, userId, isArchived);
        return Result.success(result);
    }
}
